package com.MasterDevelopers.MessageMaster;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

// Adding a comment.
public class DbAdapter {
	public static final String KEY_TITLE = "title";
	public static final String KEY_BODY = "body";
	public static final String KEY_PHONENUMBER = "phoneNumber";
	public static final String KEY_ROWID = "_id";

	private final Context mCtx;
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String TAG = "TextMaster.DbAdapter";
	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "textMessages";
	private static final String DATABASE_CREATE = "create table textMessages (_id integer primary key autoIncrement,"
			+ "title text not null, "
			+ "body text not null, "
			+ "phoneNumber text not null)";
	private static final int DATABASE_VERSION = 1;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS notes");
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public DbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the notes database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DbAdapter open() throws SQLException {
		try{
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
		}
		catch(SQLException ex){
		 throw ex;
		}
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * @param title
	 *            the title of the note
	 * @param phoneNumber
	 *            to send the message
	 * @param body
	 *            the body of the note
	 * @return rowId or -1 if failed
	 */
	public long createTextMessage(String title, String phoneNumber, String body) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_BODY, body);
		initialValues.put(KEY_PHONENUMBER, phoneNumber);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteTextMessage(long rowId) {
		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchCursorForAllTextMessages() {
		return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
				KEY_PHONENUMBER, KEY_BODY }, null, null, null, null, null);
	}
	
	public Message[] fetchAllTextMessages() {
		Cursor c = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
				KEY_PHONENUMBER, KEY_BODY }, null, null, null, null, null);
		Message[] m = new Message[c.getCount()];
		
		int i = 0;
		while(c.moveToNext()){
			m[i] = getMessageFromCursor(i, c);
			i++;
		}
		
		return m;
	}

	/**
	 * 
	 * @param rowId id of note to retrieve
	 * @return Cursor positioned to matching note, if found
	 * @throws SQLException if note could not be found/retrieved
	 */
	public Message fetchTextMessage(long rowId) throws SQLException {
		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
				KEY_PHONENUMBER, KEY_BODY }, KEY_ROWID + "=" + rowId, null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		else { return null;}


		Message m = getMessageFromCursor(rowId, mCursor);
		return m;
	}

	private Message getMessageFromCursor(long rowId, Cursor mCursor) {
		String title = mCursor.getString(mCursor
				.getColumnIndexOrThrow(DbAdapter.KEY_TITLE));
		String body = mCursor.getString(mCursor
				.getColumnIndexOrThrow(DbAdapter.KEY_BODY));
		String phoneNumber = mCursor.getString(mCursor
				.getColumnIndexOrThrow(DbAdapter.KEY_PHONENUMBER));
		
		Message m = new Message(rowId, title, body, phoneNumber);
		return m;
	}
	
    /**
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateTextMessage(long rowId, String title, String phoneNumber, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_PHONENUMBER, phoneNumber);
        args.put(KEY_BODY, body);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

}